package com.xca.is.model;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.xca.is.entity.BaiKe;
import com.xca.is.http.HttpConnect;
import com.xca.is.repository.BaiKeRepository;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class BaiKeModel extends ViewModel {
    private BaiKeRepository repository ;
    private MutableLiveData<BaiKe> liveData = new MutableLiveData<>();
    private HttpConnect httpConnect ;
    public BaiKeModel(){
        repository = null ;
    }
    public void setModel(HttpConnect httpConnect){
        this.httpConnect = httpConnect ;
        this.repository = new BaiKeRepository();
    }
    public void getData(String msg){
        repository.getData(msg)
                .subscribe(new Observer<BaiKe>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        httpConnect.Loading(true);
                        Log.d("数据获取", "数据获取中");
                    }

                    @Override
                    public void onNext(@NonNull BaiKe baiKe) {
                        if (baiKe != null){
                            liveData.postValue(baiKe);
                        }else {
                            httpConnect.Loading(false);
                            httpConnect.Error("???error???");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        httpConnect.Error(e.getMessage());
                        Log.d("数据获取", "获取失败:"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        httpConnect.Loading(false);
                        Log.d("数据获取", "获取成功");
                    }
                });
    }

    public MutableLiveData<BaiKe> getLiveData(){
        return liveData ;
    }
}
